//
//  LCHomeController.m
//  YiJun
//
//  Created by liangrongchang on 2017/4/17.
//  Copyright © 2017年 Rochang. All rights reserved.
//

#import "LCHomeController.h"
#import "LCSettingController.h"
#import "BluetoothCenter.h"
#import "LCAlertTableView.h"
#import "SVProgressHUD.h"

static NSMutableArray <CLLocation *>*locations;
static BOOL openOrClose = NO;
// 是否接受数据
static BOOL isData = YES;

@interface LCHomeController ()<MAMapViewDelegate, BluetoothCenterDelegate>

// change language label
@property (weak, nonatomic) IBOutlet UILabel *currentLu;
@property (weak, nonatomic) IBOutlet UILabel *allLu;
@property (weak, nonatomic) IBOutlet UILabel *temp;
@property (weak, nonatomic) IBOutlet UILabel *dianliu;
@property (weak, nonatomic) IBOutlet UILabel *dianliang;


@property (weak, nonatomic) IBOutlet UILabel *currentLuLabel;
@property (weak, nonatomic) IBOutlet UILabel *speedLabel;
@property (weak, nonatomic) IBOutlet UILabel *allLuLabel;
@property (weak, nonatomic) IBOutlet UILabel *dianLabel;
@property (weak, nonatomic) IBOutlet UILabel *tempLabel;
@property (weak, nonatomic) IBOutlet UILabel *dianliuLabel;

@property (weak, nonatomic) IBOutlet UIImageView *pointerImageView;
@property (weak, nonatomic) IBOutlet UIButton *openButton;

@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIButton *leftButton;
@property (nonatomic, strong) NSMutableArray <CLLocation *>*locations;
@property (nonatomic, strong) MAMapView *mapView;

@property (nonatomic ,assign) NSInteger currentDianL;
@end

@implementation LCHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.currentDianL = 101;
    // change language label
    self.currentLu.text = Language(@"本次里程(km)");
    self.allLu.text = Language(@"累计里程(km)");
    self.temp.text = Language(@"温度(°C)");
    self.dianliu.text = Language(@"电流(A)");
    self.dianliang.text = Language(@"电量(%)");
    [self.openButton setTitle:Language(@"关机") forState:UIControlStateNormal];
    [self.openButton setTitle:Language(@"开机") forState:UIControlStateSelected];
    
    
    
    UIImageView *titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]];
    titleView.frame = CGRectMake(0, 0, 30, 30);
    self.navigationItem.titleView = titleView;
    [self setupNavBar];
    [BluetoothCenter shareInstance].delegate = self;
    [[BluetoothCenter shareInstance] scanperipheral];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bluetoothChangeState:) name:BluetoochStatusChange object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bluetoochConnectPeripher:) name:BluetoochConnectPeripher object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bluetoochReadData) name:BluetoochReadData object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupNavBar {
    self.rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [self.rightButton setImage:Image(@"连接") forState:UIControlStateNormal];
    [self.rightButton addTarget:self action:@selector(showBluetoothList) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [self.leftButton setImage:Image(@"设置icon") forState:UIControlStateNormal];
    [self.leftButton addTarget:self action:@selector(goToSetting) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
}

#pragma mark - response
- (void)showBluetoothList {
    if ([BluetoothCenter shareInstance].isBluetoothOpen) {
        [[LCAlertTableView getAlertTableView] showWihtTitle:Language(@"蓝牙")];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:Language(@"打开蓝牙来允许连接到配件") message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *set = [UIAlertAction actionWithTitle:Language(@"设置") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:Language(@"好") style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:set];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)goToSetting {
    LCSettingController *setVc = [[LCSettingController alloc] init];
    [self.navigationController pushViewController:setVc animated:YES];
}

- (IBAction)openButton:(UIButton *)sender {
    if ([[BluetoothCenter shareInstance] setupTurn:openOrClose]) {
        sender.selected = !sender.selected;
        if (!openOrClose) {
            isData = NO;
            [self clearData];
        } else {
            isData = YES;
        }
        openOrClose = !openOrClose;
        if (sender.selected) {

            [self.openButton setTitle:@"开机" forState:UIControlStateNormal];
            [self clearData];

        } else {
            [self.openButton setTitle:@"关机" forState:UIControlStateSelected];
        }
    }
}

+ (NSMutableArray <CLLocation *>*)getLocationArray {
    return locations;
}

#pragma mark - NSNotificationCenter
- (void)bluetoothChangeState:(NSNotification *)noti {
    NSString *state = noti.object;
    if ([state isEqualToString:@"1"]) {
        [[LCAlertTableView getAlertTableView] showWihtTitle:Language(@"蓝牙")];
    }
}

- (void)bluetoochConnectPeripher:(NSNotification *)noti {
    // location
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.delegate = self;
    
    self.openButton.selected = YES;
}

- (void)bluetoochReadData {
    BluetoothCenter *center = [BluetoothCenter shareInstance];
    
    if (center.dianliang.length) {
        self.currentDianL = self.currentDianL >= [center.dianliang integerValue] ? [center.dianliang integerValue] : self.currentDianL;
    }

    self.currentLuLabel.text = center.currentLu.length ? center.currentLu : @"0.00";
    self.speedLabel.text = center.speed.length ? center.speed : @"0.0";
    self.allLuLabel.text = center.allLu.length ? center.allLu : @"0.00";
    self.dianLabel.text = center.dianliang.length ? [NSString stringWithFormat:@"%ld%%", (long)self.currentDianL] : @"0";
    self.tempLabel.text = center.temp.length ? center.temp : @"0.00";
    self.dianliuLabel.text = center.dianliu.length ? center.dianliu : @"0.00";
    [self pointerRorate:center.speed];
}

- (void)clearData {
    self.currentLuLabel.text = @"0.00";
    self.speedLabel.text = @"0.0";
    self.allLuLabel.text = @"0.00";
    self.dianLabel.text = @"0";
    self.tempLabel.text = @"0.00";
    self.dianliuLabel.text = @"0.00";
    [self pointerRorate:@"0"];
}

- (void)pointerRorate:(NSString *)dataStr {
    CGFloat rotation = M_PI / 20.0 * dataStr.doubleValue;
    [UIView animateWithDuration:0.2 animations:^{
        self.pointerImageView.transform = CGAffineTransformMakeRotation(rotation);
    }];
}

#pragma mark - MAMapViewDelegate
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    CLLocationCoordinate2D coor = userLocation.location.coordinate;
    //    NSLog(@"mapView--lat:%f; lon:%f", coor.latitude, coor.longitude);
    if (!userLocation.location) {
        return;
    }
    if (self.locations.count) {
        CLLocation *location = self.locations.lastObject;
        // 计算2点距离
        MAMapPoint point1 = MAMapPointForCoordinate(CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude));
        MAMapPoint point2 = MAMapPointForCoordinate(CLLocationCoordinate2DMake(coor.latitude, coor.longitude));
        CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2);
        //        NSLog(@"更新点距离:%f", distance);
        if (distance > 10 && distance < 100) {
            [self.locations addObject:userLocation.location];
        }
    } else {
        [self.locations addObject:userLocation.location];
    }
    locations = self.locations;
}


#pragma mark - getter
- (NSMutableArray<CLLocation *> *)locations {
    if (!_locations) {
        _locations = [[NSMutableArray alloc] init];
    }
    return _locations;
}

@end
